package es.aa.android.cartomatic.appview.dialog;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import es.aa.android.cartomatic.R;
import es.aa.android.cartomatic.domain.Card;
import es.aa.android.cartomatic.domain.Deck;
import es.aa.android.cartomatic.domain.Entity;
import es.aa.android.cartomatic.implementations.da.SQLiteAccess;

public class CreateDialog extends DialogFragment {

	public static final String ITEM_TO_CREATE = "item_to_create";
	public static final int CREATE_DECK = 1;
	public static final int CREATE_CARD = 2;
	
    private View rootView;
    private EditText title;
    private EditText description;
    private Button pickImage;
    private ImageView prwImage;
    private Bitmap bitmap;
    private Button done;
    
    private Intent intent;
    private String storagePath;
    private File path;

    public static CreateDialog newInstance() {
        CreateDialog dialog = new CreateDialog();
        return dialog;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        getDialog().setTitle("Creacion");
        rootView = inflater.inflate(R.layout.create, container, false);
        initElements();

        return rootView;
    }

    private void initElements() {
        title = (EditText) rootView.findViewById(R.id.editTextCardCreatorTitle);
        description = (EditText) rootView.findViewById(R.id.editTextCardCreatorDescription);
        pickImage = (Button) rootView.findViewById(R.id.buttonCardCreatorSelectImage);
        prwImage = (ImageView) rootView.findViewById(R.id.imageViewCardCreator);
        done = (Button) rootView.findViewById(R.id.buttonCardCreatorDone);

        storagePath = Environment.getExternalStorageDirectory() + "/CartoMatic/image_preview";
        path = new File(storagePath);

        pickImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getImageDialog();
            }
        });

        done.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(writeItem()) {
                    dismiss();
                }
            }
        });
        
    }

	private static int TAKE_PICTURE = 1;
    private static int SELECT_PICTURE = 2;

    private void getImageDialog() {
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                getActivity());
        alertDialog.setTitle("Opciones de imagen");
        String[] otions = {"Galeria", "Camara"};

        alertDialog.setItems(otions,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        if (which == 0) {
                            intent = new Intent(
                                    Intent.ACTION_PICK,
                                    MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                            startActivityForResult(intent, SELECT_PICTURE);
                        } else if (which == 1) {
                            Uri output = Uri.fromFile(path);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    output);
                            startActivityForResult(intent, TAKE_PICTURE);
                        }
                    }
                }
        );
        alertDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Se revisa si la imagen viene de la c�mara (TAKE_PICTURE) o de la galer�a (SELECT_PICTURE)
        if (requestCode == TAKE_PICTURE) {

            // A partir del nombre del archivo ya definido lo buscamos y
            // creamos el bitmap para el ImageView;
            bitmap = BitmapFactory.decodeFile(storagePath);

            // Para guardar la imagen en la galer�a, utilizamos una
            // conexi�n a un MediaScanner
            new MediaScannerConnectionClient() {
                private MediaScannerConnection msc = null;

                {
                    msc = new MediaScannerConnection(
                            getActivity(), this);
                    msc.connect();
                }

                public void onMediaScannerConnected() {
                    msc.scanFile(storagePath, null);
                }

                public void onScanCompleted(String path, Uri uri) {
                    msc.disconnect();
                }
            };

            // Recibimos el URI de la imagen y construimos un Bitmap a partir de un stream de Bytes
        } else if (requestCode == SELECT_PICTURE) {
            Uri selectedImage;
            InputStream is;
            BufferedInputStream bis;
            try {
                if (data != null) {
                    selectedImage = data.getData();
                    is = getActivity().getContentResolver().openInputStream(selectedImage);
                    bis = new BufferedInputStream(is);
                    bitmap = BitmapFactory.decodeStream(bis);
                }
            } catch (FileNotFoundException e) {

            }
        }
        if (bitmap != null) {
            //bitmap = Resizer.bitmap(bitmap, 250);
        	//bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
            prwImage.setImageBitmap(bitmap);
            prwImage.setVisibility(View.VISIBLE);
            
        }
    }

	private boolean writeItem() {
		int option = getActivity().getIntent().getExtras()
				.getInt(ITEM_TO_CREATE);

		Entity e = null;
		String txtTitle = title.getText().toString();
		String txtDescription = description.getText().toString();

		switch (option) {
			case CREATE_DECK:
				e = new Deck();
				break;
	
			case CREATE_CARD:
				e = new Card();
				break;
	
			default:
				break;
		}

		if (!txtTitle.equals("")) {
			e.setName(txtTitle);
			if (!txtDescription.equals("")) {
				e.setDescription(txtDescription);
				if (bitmap != null) {
					e.setImage(bitmap);
					SQLiteAccess sqLiteAccess = new SQLiteAccess();
					
					switch (option) {
					
						case CREATE_DECK:
							
							sqLiteAccess.writeDeck(getActivity().getApplicationContext(), (Deck) e);
							break;
							
						case CREATE_CARD:
							
							sqLiteAccess.writeCard(getActivity().getApplicationContext(), (Card) e);
							break;
							
						default:
							break;
					}
					
					return true;
					
				}
			}
		}
        
        Toast.makeText(getActivity().getApplicationContext(), "Debe rellenar todos los campos", Toast.LENGTH_SHORT).show();
        return false;
    }

    public static void makeDialog(Activity activity) {
        FragmentTransaction ft = ((FragmentActivity) activity).getSupportFragmentManager().beginTransaction();
        CreateDialog dialog = CreateDialog.newInstance();
        dialog.show(ft, "DIALOG");
    }
}
